import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-04-03
 * Time: 15:50
 */

public class Test {
    /**
     * 力扣题
     * https://leetcode.cn/problems/evaluate-reverse-polish-notation/description/
     */
    //波兰表达式求和
    //tokens = ["2","1","+","3","*"]
    public static void main2(String[] args) {
        String[] str = {"2", "1", "+", "3", "*"};
        System.out.println(evalRPN(str));

    }

    public static int evalRPN(String[] tokens) {

        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < tokens.length; i++) {
            String tmp = tokens[i];
            if (!isOperation(tmp)) {
                //如果不是操作符
                Integer val = Integer.valueOf(tmp);
//                Integer val = Integer.parseInt(tmp.trim());
                stack.push(val);
            } else {
                Integer val2 = stack.pop();
                Integer val1 = stack.pop();
                switch (tmp) {
                    case "+":
                        stack.push(val1 + val2);
                        break;
                    case "-":
                        stack.push(val1 - val2);
                        break;
                    case "*":
                        stack.push(val1 * val2);
                        break;
                    case "/":
                        stack.push(val1 / val2);
                        break;
                }
            }
        }
        return stack.pop();
    }


    //判断是否为操作符
    public static boolean isOperation(String s) {
        if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) {
            return true;
        }
        return false;
    }

    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     * 思路: 遍历pushv数组,入栈,每入栈一个元素判断栈顶元素是不是和popv如果不一样继续遍历pushv入栈
     * 如果一样,弹出栈顶元素,popv的j++
     *
     * @param pushV int整型一维数组
     * @param popV  int整型一维数组
     * @return bool布尔型
     */
    public boolean IsPopOrder(int[] pushV, int[] popV) {
        // write code here
        Stack<Integer> stack = new Stack<>();
        int j = 0;//遍历popv
        for (int i = 0; i < pushV.length; i++) {
            stack.push(pushV[i]);//先入栈,再判断
            while (j < popV.length && !stack.empty() && popV[j] == stack.peek()) {
                //j不能越界,并且栈不为空
                stack.pop();
                j++;
            }
        }
        return stack.empty();//判断最后的栈是不是空
    }
}

